package com.sgb.kjwl.view.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.webkit.WebView;

import com.swgk.core.util.LogUtil;

public class ScrollWebView extends WebView {
    public OnScrollChangeListener listener;
    private OnTouchListener touchListener;

    public ScrollWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public ScrollWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ScrollWebView(Context context) {
        super(context);
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {

        super.onScrollChanged(l, t, oldl, oldt);

        float webcontent = getContentHeight() * getScale();// webview的高度
        float webnow = getHeight() + getScrollY();// 当前webview的高度
        LogUtil.i("TAG1", "webview.getScrollY()====>>" + getScrollY());
        if (listener != null) {
            if (Math.abs(webcontent - webnow) < 1) {
                // 已经处于底端
                // Log.i("TAG1", "已经处于底端");
                listener.onPageEnd(l, t, oldl, oldt);
            } else if (getScrollY() == 0) {
                // Log.i("TAG1", "已经处于顶端");
                listener.onPageTop(l, t, oldl, oldt);
            } else {
                listener.onScrollChanged(l, t, oldl, oldt);
            }
        }

    }

    public void setOnScrollChangeListener(OnScrollChangeListener listener) {

        this.listener = listener;

    }

    public interface OnScrollChangeListener {
        void onPageEnd(int l, int t, int oldl, int oldt);

        void onPageTop(int l, int t, int oldl, int oldt);

        void onScrollChanged(int l, int t, int oldl, int oldt);

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        float webcontent = getContentHeight() * getScale();// webview的高度
        float webnow = getHeight() + getScrollY();// 当前webview的高度
        LogUtil.i("TAG3", "webview.getScrollY()====>>" + getScrollY());

        if (touchListener != null) {
            // 已经处于底端 和顶端
            if (event.getAction() == MotionEvent.ACTION_UP) {
                touchListener.onTouchStart();
            } else {
                if (Math.abs(webcontent - webnow) < 1 || getScrollY() == 0) {
                    touchListener.onTouchStart();
                } else {
                    touchListener.onTouchEnd();
                }
            }
        }
        return false;
    }

    public void setOnTouchListener(OnTouchListener listener) {

        this.touchListener = listener;

    }

    public interface OnTouchListener {
        void onTouchStart();

        void onTouchEnd();

    }
}